﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FunnyFunction
{
    class Poker_JFirst
    {
        public static void Play()
        {
            Pokers pks = Pokers.Init();
            Console.WriteLine("开始...");
            pks.Shuffle();
            pks.Cut();

            var list = pks.Send(2);
            var p1 = list[0];
            var p2 = list[1];

            Console.WriteLine("  --玩家1: J-" + p1.Count(p => p.num == "J") + "张, Joker:" + p1.Count(p => p.num.ToLower() == "joker") + "张");
            Console.WriteLine("  --玩家2: J-" + p2.Count(p => p.num == "J") + "张, Joker:" + p2.Count(p => p.num.ToLower() == "joker") + "张");
            Console.WriteLine("-------------");

            int sum = 0;
            int pt = 0;
            List<Poker> DList = new List<Poker>();
            while (true)
            {
                sum++;
                if(p1.Count==0 || p2.Count==2)
                {
                    break;
                }
                Console.Write(pt);

                var pk = Take1(list[pt]);
                DList.Add(pk);
                var ll = CheckDesk(DList);
                if (ll.Count > 0)
                {
                    DList.RemoveRange(DList.Count - ll.Count, ll.Count);
                    list[pt].AddRange(ll);
                }
                else
                {
                    pt += 1;
                    if (pt >= list.Count) pt = 0;
                }
            }
            Console.WriteLine(""); 
            Console.WriteLine("-------------");
            var win = "";
            if (p1.Count > 0)
                win = "1";
            else
                win = "2";
            Console.WriteLine($"游戏结束,出牌次数：{sum}, 玩家{win} 获胜！");
        }

        private static List<Poker> CheckDesk(List<Poker> dList)
        {
            List<Poker> ll = new List<Poker>();
            if (dList.Count <= 2)
            {
                return ll;
            }
            var last = dList.Last();
            if (last.num == "J" || last.num.ToString() == "joker")
            {
                ll = dList;
            }
            else
            {
                for (int i = 0; i < dList.Count - 1; i++)
                {
                    if (dList[i].num.ToLower() == last.num.ToLower())
                    {
                        ll = dList.Skip(i).ToList();
                        break;
                    }
                }
            }
            return ll;
        }

        private static T Take1<T>(List<T> tList)
        {
            var t = tList[0];
            tList.RemoveAt(0);
            return t;
        }
    }
}
